package com.welab.helloworld.service;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HelloWorldService {

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    private final static String processDefinitionKey = "helloworld";

    public Object startProcess() {
        //String processDefinitionKey = "helloworld";
        ProcessInstance pi = runtimeService// 与正在执行 的流程实例和执行对象相关的Service
                .startProcessInstanceByKey(processDefinitionKey); // 使用流程定义的key启动流程实例,key对应helloworld.bpmn文件中id的属性值，使用key值启动，默认是按照最新版本的流程定义启动
        Map<String, Object> map = new HashMap<>();
        map.put("pi.getProcessDefinitionKey()", pi.getProcessDefinitionKey());
        map.put("pi.getProcessDefinitionId()", pi.getProcessDefinitionId());
        map.put("pi.getProcessInstanceId()", pi.getProcessInstanceId());
        map.put("pi.getDeploymentId()", pi.getDeploymentId());
        map.put("pi.getProcessDefinitionName()", pi.getProcessDefinitionName());
        map.put("pi.getName()", pi.getName());
        return map;
    }

    public Object getTasks() {
        List<String> list = new ArrayList<>();
        for (Task t : taskService.createTaskQuery().taskAssignee("张三").processDefinitionKey(processDefinitionKey).list()) {
            list.add(t.getId());
        }
        return list;
    }

    public Object claim() {
        taskService.createTaskQuery().taskAssignee("张三").processDefinitionKey(processDefinitionKey).list().forEach(task -> {
            taskService.claim(task.getId(), "李四");
        });
        return "ok";
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Object complete(String assignee) {
        List<String> list = new ArrayList<>();
        taskService.createTaskQuery().taskAssignee(assignee).processDefinitionKey(processDefinitionKey).list().forEach(task -> {
            list.add(task.getId());
            taskService.complete(task.getId());
        });
        //int i = 1 / 0;
        return list;
    }
}
